package com.wrial.simple;
/*
 * @Author  Wrial
 * @Date Created in 11:12 2020/3/31
 * @Description 反转一个单链表。
 * 输入: 1->2->3->4->5->NULL
   输出: 5->4->3->2->1->NULL
 */

import java.util.List;

public class LeetCode_206 {
    public ListNode reverseList(ListNode head) {

        ListNode ans = new ListNode(-1);


        ListNode current = head;
        while (current != null) {
            // 用于链表的向后移动，否则就只能移动第一个元素
            ListNode nextNode = current.next;
            // 此处会将currentNext覆盖，所有就会遍历不到后面
            current.next = ans.next;
            ans.next = current;
            // 向后
            current = nextNode;
        }
        return ans.next;

    }

    public static class ListNode {
        int val;
        ListNode next;

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }

        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(1);
        node.next = new ListNode(2);
        node.next.next = new ListNode(3);
        node.next.next.next = new ListNode(4);
        node.next.next.next.next = new ListNode(5);
        ListNode node1 = new LeetCode_206().reverseList(node);
        System.out.println(node1.toString());


    }


}
